package team.pwy.controller;

import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import team.pwy.mapper.SeckillMapper;
import team.pwy.pojo.entity.Seckill;
import team.pwy.service.SeckillService;
import team.pwy.vo.Result;

import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("seckill")
public class SeckillController {

    @Resource
    private SeckillService seckillService;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private SeckillMapper seckillMapper;

    @GetMapping
    public Result findAll() {
        List<Seckill> seckillList = seckillService.findAll();
        return seckillList != null ? new Result("200", "查询成功", seckillList) : new Result("400", "查询失败");
    }

    //    秒杀
    @GetMapping("/before")
    public Result load() {
        return seckillService.findBeforeActiveIds() ? new Result("200", "加载商品") : new Result("400", "没有商品参与秒杀");
    }

    @GetMapping("/start")
    public Result active() {
        return seckillService.updateActiveStatus() ? new Result("200", "秒杀活动开始") : new Result("400", "没有商品在进行中!");
    }

    @GetMapping("/end")
    public Result end() {
        return seckillService.updateEndStatus() ? new Result("200", "秒杀活动结束") : new Result("400", "没有商品结束");
    }

    @GetMapping("{userId}/{secId}")
    public Result hello(@PathVariable("userId") Integer userId, @PathVariable("secId") Integer secId) {

        //判断秒杀活动是否已经开始
        String status = seckillService.getStatus(secId);
//        Integer status = seckillMapper.findStatus(secId);
        if ("0".equals(status)) {
            return new Result("501", "活动尚未开始");
        }
        // 判断秒杀活动是否已经结束了
        if ("2".equals(status)) {
            return new Result("503", "活动已经结束");
        }

        //正常可以秒杀

        Integer goods = seckillMapper.findGoods(secId);
        if (goods<=0){
            return new Result("502", "已经售罄了");
        }
//        Integer o = (Integer) redisTemplate.opsForList().leftPop("sec_" + secId);
        //判断o是否null
//        if (Objects.isNull(o)) {
//            return new Result("502", "已经售罄了");
//        }

        //正常入手... 判断是否属于重复抢购
        //sec_result_1   ["admin","tom"]
        SetOperations set = redisTemplate.opsForSet();
        //判断set集合中是否已经出现过这个人
        if (set.isMember("sec_result_" + secId, userId)) {
            return new Result("201", "不能够重复抢购");
        } else {
            set.add("sec_result_" + secId, userId);

            //投递到rbm中
            seckillService.sendRbm(userId, secId);
            return new Result("200", "恭喜您,抢购成功");
        }
    }
}
